package com.yipao.admin.service;

import com.alibaba.fastjson.JSONObject;
import com.yipao.admin.map.LbsStoreDeleteReq;
import com.yipao.admin.map.LbsStoreSaveReq;
import com.yipao.admin.map.LbsStoreSelectReq;
import com.yipao.admin.vo.lbs.LbsLocationVo;
import com.yipao.admin.vo.lbs.LbsStoreUpdateVo;
import com.yipao.admin.vo.lbs.LbsStoreVo;
import com.yipao.core.system.LbsConstant;
import com.yipao.core.util.HttpClientUtil;
import com.yipao.core.util.HttpUtil;
import com.yipao.core.util.ResponseUtil;
import com.yipao.db.domain.devinfo.DevInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yipao.admin.util.AdminResponseCode.MAP_ABNORMAL;

/**
 * 腾讯地图云存储API
 *
 * @author y.x
 * @date 2019/9/16
 */
@Service
@Slf4j
public class LbsTableService {
    @Value("${lbs.qq.tableId}")
    private String lasQqTableId;

    @Value("${lbs.qq.key}")
    private String lasQqKey;

    @Value("$(lbs.qq.radius)")
    private String radius;


    /**
     * 创建数据（create）接口
     * 通过本接口，可向地点云指定数据表存入一条或多条数据
     * 缺失坐标时通过地址（address）自动计算：
     * 地点云数据中location（坐标）为必填字段，但当您的数据只有地址(address)而无location(坐标)时，
     * 服务会调用地址解析服务通过address计算坐标，为保证坐标尽可能准确，结果会取可信度与精度较高的结果（reliabylity>=7且level>=9，可参考：地址解析服务文档），未达到这一标准的结果将无法创建成功。
     *
     * @param model
     * @return
     */
    public Object insert(DevInfo model) {
        try {

            List<LbsStoreVo> list = new ArrayList<>();
            //传入设备实体类 将id ,和名字封装进lbsStoreVo
            list.add(new LbsStoreVo(model.getScenes(), String.valueOf(model.getId()),
                    //设备地址 经纬度  手机号封装进LbsLocationVo
                    new LbsLocationVo(Double.parseDouble(model.getLat()), Double.parseDouble(model.getLng())), model.getAddress(), model.getPhone()));
            //传入开发者key table_id 以及数据
            LbsStoreSaveReq lbsStoreReq = new LbsStoreSaveReq(lasQqKey, lasQqTableId, list);
            String s1 = JSONObject.toJSONString(lbsStoreReq);
            log.debug(s1);
            //发起http请求
            String s = HttpUtil.doPost(LbsConstant.TABLE_CREATE, s1);
            log.debug(s);
            return ResponseUtil.ok(s);
        } catch (Exception e) {
            log.error("腾讯地图云存储新增异常", e);
            return ResponseUtil.fail(MAP_ABNORMAL, "新增异常");
        }
    }


    /**
     * 修改
     *
     * @param model
     * @return
     */
    public Object update(DevInfo model) {

        try {
            LbsStoreVo data = new LbsStoreVo();
            data.setName(model.getScenes());
            data.setLocation(new LbsLocationVo(Double.parseDouble(model.getLat()), Double.parseDouble(model.getLng())));
            data.setAddress(model.getAddress());
            data.setTel(model.getPhone());
            LbsStoreUpdateVo vo = new LbsStoreUpdateVo(data, lasQqTableId, lasQqKey);


            String ss = "ud_id in(\"" + model.getId() + "\")";
            vo.setFilter(ss);

            log.debug(JSONObject.toJSONString(vo));
            String str = HttpUtil.doPost(LbsConstant.TABLE_UPDATE, JSONObject.toJSONString(vo));
            log.debug("腾讯地图云存储 修改 返回结果", JSONObject.toJSONString(str));
            JSONObject jsonObject = JSONObject.parseObject(str);

            if (0 == jsonObject.getInteger("status")) {
                // 修改 成功条数为0
                if (jsonObject.getJSONObject("result").getInteger("count") == 0) {
                    insert(model);
                }
            }
            return ResponseUtil.ok();
        } catch (Exception e) {
            log.error("腾讯地图云存储 修改异常", e);
            return ResponseUtil.fail(MAP_ABNORMAL, "修改异常");
        }
    }


    public Object deleteById(String id) {
        try {
            LbsStoreDeleteReq req = new LbsStoreDeleteReq();
            String ss = "ud_id in(\"" + id + "\")";


            req.setFilter(ss);
            req.setTable_id(lasQqTableId);
            req.setKey(lasQqKey);
            log.debug("腾讯地图云存储 删除接口 请求参数:{}", req.toString());
            String s = HttpUtil.doPost(LbsConstant.TABLE_DELETE, JSONObject.toJSONString(req));
            log.debug(s);
            return ResponseUtil.ok("删除成功");
        } catch (Exception e) {
            log.error("腾讯地图云存储 删除数据异常{}", e);
            return ResponseUtil.fail(MAP_ABNORMAL, "删除异常");
        }
    }


    public Object list() {
        LbsStoreSelectReq req = new LbsStoreSelectReq();
        req.setKey(lasQqKey);
        req.setTable_id(lasQqTableId);

        Map<String, String> map = new HashMap<>(2);
        map.put("table_id", lasQqTableId);
        map.put("key", lasQqKey);
        return HttpUtil.sendGet(LbsConstant.TABLE_LIST, map);
    }

    /**
     * 附近搜索
     *
     * @param name
     * @param location
     * @return
     */
    public Object searchNearby(String name, String location) {
        try {
            if (StringUtils.isBlank(location)) {
                log.error("地址输入有误");
                return ResponseUtil.fail(402, "请选择当前位置");
            }
            StringBuilder sb = new StringBuilder();
            sb.append(LbsConstant.NEARBY_SEARCH_URL + "?");
            if (StringUtils.isBlank(name)) {
                sb.append("keyWord=" + name + "&");
            }
            sb.append("location=" + location +
                    "&radius=3000&page_size=5&table_id=" + lasQqTableId + "&key=" + lasQqKey);
            String result = HttpClientUtil.get(sb.toString());
            log.debug(result);
            return result;
        } catch (Exception e) {
            log.error("searchNearby exception", e);
            return ResponseUtil.fail(MAP_ABNORMAL, "查询异常");
        }
    }


}
